import axios, { AxiosResponse, AxiosError, InternalAxiosRequestConfig } from 'axios';
import { message } from 'antd';
import { useAuthStore } from '@/stores/authStore';
import type { ApiResponse } from '@/types';

// 创建axios实例https://api.xlcig.cn/api
const http = axios.create({
  baseURL: 'https://api.xlcig.cn/api', // 直接调用线上API
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
http.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 添加认证token
    const token = useAuthStore.getState().token;
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    // //如果是删除请求 不管什么用户 直接拦截
    // if (config.method === 'delete') {
    //   return config;
    // }
    // 添加请求时间戳
    config.headers['X-Request-Time'] = Date.now().toString();

    console.log('🚀 Request:', {
      method: config.method?.toUpperCase(),
      url: config.url,
      data: config.data,
      params: config.params,
    });

    return config;
  },
  (error: AxiosError) => {
    console.error('❌ Request Error:', error);
    message.error('请求配置错误');
    return Promise.reject(error);
  }
);

// 响应拦截器
http.interceptors.response.use(
  (response: AxiosResponse<ApiResponse>) => {
    const { data } = response;
    console.log('✅ Response:', {
      status: response.status,
      url: response.config.url,
      data: data,
    });

    // 检查业务状态码
    if (data.success !== undefined) {
      if (data.success) {
        // 成功响应
        return response;
      } else {
        // 业务错误
        message.error(data.message || '请求失败');
        return Promise.reject(new Error(data.message || 'Request failed'));
      }
    }

    return response;
  },
  (error: AxiosError<ApiResponse>) => {
    console.error('❌ Response Error:', error);

    // 网络错误处理
    if (!error.response) {
      if (error.code === 'ECONNABORTED') {
        message.error('请求超时，请稍后重试');
      } else if (error.message.includes('Network Error')) {
        message.error('网络连接失败，请检查网络');
      } else {
        message.error('请求失败，请稍后重试');
      }
      return Promise.reject(error);
    }

    // HTTP状态码错误处理
    const { status, data } = error.response;
    
    switch (status) {
      case 400:
        message.error(data?.message || '请求参数错误');
        break;
      case 401:
        message.error('认证失败，请重新登录');
        useAuthStore.getState().logout();
        window.location.href = '/login';
        break;
      case 403:
        message.error('无权限访问');
        break;
      case 404:
        message.error('请求的资源不存在');
        break;
      case 422:
        message.error(data?.message || '数据验证失败');
        break;
      case 429:
        message.error('请求过于频繁，请稍后重试');
        break;
      case 500:
        message.error('服务器内部错误');
        break;
      case 502:
        message.error('网关错误');
        break;
      case 503:
        message.error('服务暂时不可用');
        break;
      case 504:
        message.error('网关超时');
        break;
      default:
        message.error(data?.message || `请求失败 (${status})`);
    }

    return Promise.reject(error);
  }
);

// 便捷方法
export const httpGet = <T = any>(url: string, params?: any): Promise<AxiosResponse<ApiResponse<T>>> => {
  return http.get(url, { params });
};

export const httpPost = <T = any>(url: string, data?: any): Promise<AxiosResponse<ApiResponse<T>>> => {
  return http.post(url, data);
};

export const httpPut = <T = any>(url: string, data?: any): Promise<AxiosResponse<ApiResponse<T>>> => {
  return http.put(url, data);
};

export const httpDelete = <T = any>(url: string, params?: any): Promise<AxiosResponse<ApiResponse<T>>> => {
  return http.delete(url, { params });
};

export const httpPatch = <T = any>(url: string, data?: any): Promise<AxiosResponse<ApiResponse<T>>> => {
  return http.patch(url, data);
};

// 文件上传
export const httpUpload = <T = any>(url: string, formData: FormData, onProgress?: (progress: number) => void): Promise<AxiosResponse<ApiResponse<T>>> => {
  return http.post(url, formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
    onUploadProgress: (progressEvent) => {
      if (onProgress && progressEvent.total) {
        const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        onProgress(progress);
      }
    },
  });
};

// 文件下载
export const httpDownload = (url: string, filename?: string): Promise<void> => {
  return http.get(url, {
    responseType: 'blob',
  }).then((response) => {
    const blob = new Blob([response.data]);
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = filename || 'download';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(downloadUrl);
  });
};

export default http; 